package org.fuxia.im.gui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.tree.DefaultTreeModel;

import org.fuxia.im.common.ClientConst;
import org.fuxia.im.common.ClientContext;
import org.fuxia.im.core.ECMessageType;
import org.fuxia.im.core.entries.ECPacket;
import org.fuxia.im.core.socket.ECClient;
import org.tony.common.ui.CommonFrame;

import com.alibaba.fastjson.JSONArray;

public class FriendManage extends CommonFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L ;
	private JPanel contentPane ;
	private JTextField conditionTF ;
	private JTable table ;
	private JTree tree ;
	private String[] title = {"昵称", "账号", "地址", "分组"} ;
//	private MyTableModel model ;
	private Formater[] groups ;
	private Object[][] allData ;
	private JComboBox<Formater> group ;
	private int row ;

	/**
	 * Create the frame.
	 */
	@SuppressWarnings("serial")
	public FriendManage() {
		super() ;
		initData();
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 800, 500);
		setTitle("好友管理器") ;
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContent(contentPane);
		
		JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.CENTER);
		panel.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_1 = new JPanel();
		panel_1.setBorder(UIManager.getBorder("FormattedTextField.border"));
		panel.add(panel_1, BorderLayout.NORTH);
		
		JLabel logo = new JLabel("好友分组");
		logo.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		logo.setIcon(new ImageIcon(FriendManage.class.getResource("/images/manage1.jpg")));
		
		conditionTF = new JTextField();
		conditionTF.setBorder(UIManager.getBorder("FormattedTextField.border"));
		conditionTF.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		conditionTF.setColumns(10);
		
		JButton searchBtn = new JButton("搜索");
		searchBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
			}
		});
		searchBtn.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		GroupLayout gl_panel_1 = new GroupLayout(panel_1);
		gl_panel_1.setHorizontalGroup(
			gl_panel_1.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panel_1.createSequentialGroup()
					.addContainerGap()
					.addComponent(logo, GroupLayout.PREFERRED_SIZE, 92, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED, 428, Short.MAX_VALUE)
					.addComponent(conditionTF, GroupLayout.PREFERRED_SIZE, 164, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(searchBtn, GroupLayout.PREFERRED_SIZE, 66, GroupLayout.PREFERRED_SIZE)
					.addGap(6))
		);
		gl_panel_1.setVerticalGroup(
			gl_panel_1.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panel_1.createSequentialGroup()
					.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
						.addComponent(logo, GroupLayout.PREFERRED_SIZE, 45, GroupLayout.PREFERRED_SIZE)
						.addComponent(conditionTF, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE)
						.addComponent(searchBtn, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)))
		);
		panel_1.setLayout(gl_panel_1);
		
		JPanel panel_2 = new JPanel();
		panel.add(panel_2, BorderLayout.CENTER);
		
		JPanel panel_4 = new JPanel();
		panel_4.setBorder(UIManager.getBorder("FormattedTextField.border"));
		
		JPanel panel_3 = new JPanel();
		panel_3.setBorder(UIManager.getBorder("FormattedTextField.border"));
		GroupLayout gl_panel_2 = new GroupLayout(panel_2);
		gl_panel_2.setHorizontalGroup(
			gl_panel_2.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_2.createSequentialGroup()
					.addComponent(panel_3, GroupLayout.PREFERRED_SIZE, 208, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(panel_4, GroupLayout.DEFAULT_SIZE, 560, Short.MAX_VALUE))
		);
		gl_panel_2.setVerticalGroup(
			gl_panel_2.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_2.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_panel_2.createParallelGroup(Alignment.LEADING)
						.addComponent(panel_3, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 385, Short.MAX_VALUE)
						.addComponent(panel_4, GroupLayout.DEFAULT_SIZE, 385, Short.MAX_VALUE)))
		);
		panel_3.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_6 = new JPanel();
		panel_3.add(panel_6, BorderLayout.NORTH);
		panel_6.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		
		
		JButton addGroupBtn = new JButton("点此添加分组");
		addGroupBtn.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		panel_3.add(addGroupBtn, BorderLayout.SOUTH);
		panel_3.setBorder(new TitledBorder("好友分组"));
		
		
		tree = new JTree();
		tree.putClientProperty("JTree.lineStyle", "None" );
		tree.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		tree.setToggleClickCount(1) ;
		tree.setRootVisible(true) ;
		tree.setModel(new DefaultTreeModel(
			new MyDefaultMutableTreeNode("全部好友") {
				{
					for(Formater fmt:groups) {
						MyDefaultMutableTreeNode node = new MyDefaultMutableTreeNode();
						node.setGroupId(fmt.getGroupId()) ;
						node.setUserObject(fmt.getGroupName()) ;
						add(node);
					}
				}
				
			}
		));
		
		MouseListener lis = new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent e) {
				super.mouseClicked(e);
				MyDefaultMutableTreeNode node = (MyDefaultMutableTreeNode)tree.getLastSelectedPathComponent() ;
				if(node != null) {
					if(node.getLevel() == 1) {
						group.setEnabled(false) ;
						group.setSelectedItem(null) ;
						table.removeAll() ;
						table.setModel(new MyTableModel(getData(node.getGroupId(), node.getUserObject().toString()), title)) ;
					}else if(node.getLevel() == 0) {
						group.setEnabled(false) ;
						group.setSelectedItem(null) ;
						table.removeAll() ;
						table.setModel(new MyTableModel(allData, title)) ;
					}
					
				}

			}
		};
		tree.addMouseListener(lis) ;
		
		panel_3.add(tree, BorderLayout.CENTER);
		panel_4.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_5 = new JPanel();
		panel_4.add(panel_5, BorderLayout.NORTH);
		
		JLabel titleLab = new JLabel("全部好友");
		titleLab.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		
		JLabel modetoLab = new JLabel("移动到");
		modetoLab.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		
		group = new JComboBox<Formater>(groups);
		group.setEnabled(false) ;
		group.setSelectedItem(null) ;
		
		group.setFont(new Font("微软雅黑", Font.PLAIN, 13));

		
		group.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				Formater temp = (Formater) group.getSelectedItem() ;
				if(temp != null) {
					String groupId = temp.getGroupId();
					String groupName = temp.getGroupName() ;
					String originUserCode = ClientContext.getLoginUser().getUserCode() ;
					String friendUserCode = table.getModel().getValueAt(row, 1).toString() ;
					System.out.println(friendUserCode);
					String friendNickName = table.getModel().getValueAt(row, 0).toString() ;
					ECPacket packet = new ECPacket() ;	
					packet.setMessageType(ECMessageType.USER_FRIEND.name()) ;
					packet.addParam("option", "moveFriend") ;
					
					packet.addParam("groupId", groupId) ;
					packet.addParam("groupName", groupName) ;
					packet.setFrom(originUserCode) ;
					packet.setTo(friendUserCode) ;
					packet.addParam("friendNickName", friendNickName) ;
					ECClient client = ClientContext.getContext().getClient() ;
					try {
						client.sendMessage(packet) ;
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				}
				
				
			}
		});

	
		
		JButton addFriendBtn = new JButton("");
		addFriendBtn.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		addFriendBtn.setIcon(new ImageIcon(FriendManage.class.getResource("/images/add.jpg")));
		addFriendBtn.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent e) {
				Object obj = ClientContext.getContext().get("findFrame") ;
				FindFriend find = null ;
				if(obj != null && obj instanceof FindFriend){
					find = (FindFriend)obj ;
					find.setState(JFrame.NORMAL) ;
				}else{
					find = new FindFriend() ;
					ClientContext.getContext().put("findFrame", find) ;
					find.setVisible(true) ;
				}
			}
		}) ;
		
		JButton deleteFriendBtn = new JButton("");
		deleteFriendBtn.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		deleteFriendBtn.setIcon(new ImageIcon(FriendManage.class.getResource("/images/delete.jpg")));
		GroupLayout gl_panel_5 = new GroupLayout(panel_5);
		gl_panel_5.setHorizontalGroup(
			gl_panel_5.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_5.createSequentialGroup()
					.addContainerGap()
					.addComponent(titleLab, GroupLayout.PREFERRED_SIZE, 83, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED, 211, Short.MAX_VALUE)
					.addComponent(modetoLab, GroupLayout.PREFERRED_SIZE, 48, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addComponent(group, GroupLayout.PREFERRED_SIZE, 118, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addComponent(addFriendBtn, GroupLayout.PREFERRED_SIZE, 27, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(deleteFriendBtn, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE)
					.addContainerGap())
		);
		gl_panel_5.setVerticalGroup(
			gl_panel_5.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panel_5.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_panel_5.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_panel_5.createParallelGroup(Alignment.BASELINE)
							.addComponent(titleLab, GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
							.addComponent(group, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
							.addComponent(modetoLab))
						.addComponent(deleteFriendBtn, Alignment.TRAILING)
						.addComponent(addFriendBtn, Alignment.TRAILING)))
		);
		panel_5.setLayout(gl_panel_5);
		
		JScrollPane scrollPane = new JScrollPane();
		panel_4.add(scrollPane, BorderLayout.CENTER);
		
		table = new JTable();
		table.setModel(new MyTableModel(allData,title));
		table.setFont(new Font("微软雅黑", Font.PLAIN, 13));
		
		
		MouseListener ml = new MouseAdapter(){

			@Override
			public void mouseClicked(MouseEvent e) {
				super.mouseClicked(e);
				if(e.getClickCount() == 1) {
					row = table.getSelectedRow();
					if(row>-1) {
						System.out.println(row);
						group.setEnabled(true) ;
					}
				}
			}
		};
		
		table.addMouseListener(ml) ;
		
		scrollPane.setViewportView(table);
		panel_2.setLayout(gl_panel_2);
	}
	
	
	
	public void  initData() {
		

		@SuppressWarnings("unchecked")
		Map<String,List<Object>> map = ClientContext.getValue(ClientConst.FRIENDS, Map.class) ;
		int count = 0 ;
		int i = 0 ;
		Iterator<String> keyIter = map.keySet().iterator();
		Formater[] groups = new Formater[map.keySet().size()] ;
		while(keyIter.hasNext()) {
			String key = keyIter.next();
			count += map.get(key).size();
			String[] fg = key.split("#") ;
			Formater fm = new Formater(fg[1],fg[0]) ;
			groups[i++] = fm ; 
		}
		
		this.groups = groups ;
		Object[][] allFriends = new Object[count][4] ;
		System.out.println(count);
		Iterator ite = map.entrySet().iterator() ;
		int k = 0;
		while(ite.hasNext()){
			Entry entry = (Entry) ite.next() ;
			String key = entry.getKey().toString() ;
			String[] group = key.split("#") ;
			JSONArray value = (JSONArray) entry.getValue();
			for(int j=0; j<value.size();j++){
				JSONArray o = (JSONArray) value.get(j);
				System.out.println(j);
				allFriends[k][0] = o.get(1) ;
				allFriends[k][1] = o.get(0) ;
				allFriends[k][2] = o.get(6) ;
				allFriends[k][3] = group[1] ;
				k++ ;
				
			}
		}
		this.allData = allFriends;
	}
	
	public Formater getFormater(String groupName) {
		for(Formater fmt:groups) {
			if(fmt.getGroupName().equals(groupName)) {
				return fmt ;
			}
		}
		return null ;
	}
	
	public Object[][] getData(String groupId, String groupName) {
		String groupKey = groupId + "#" + groupName ;
		Map<String,List<Object>> map = ClientContext.getValue(ClientConst.FRIENDS, Map.class) ;
		List<Object> friends = map.get(groupKey) ;
		Object[][] data = new Object[friends.size()][4] ;
		for(int i = 0; i < friends.size(); i++) {
			JSONArray friend = (JSONArray) friends.get(i) ;
			data[i][0] = friend.get(1) ;
			data[i][1] = friend.get(0) ;
			data[i][2] = friend.get(6) ;
			data[i][3] = groupName ;
		}
		return data ;
	}
	
	public void setTableData() {
		table.removeAll() ;
		initData() ;
		table.setModel(new MyTableModel(allData,title)) ;
	}
}
